package com.lagou.executor;

import com.lagou.pojo.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author liujunling
 * @date 2020/3/31
 */
public class SimpleExecutor implements Executor {
    private Configuration configuration;

    public SimpleExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <T> List<T> query(MappedStatement mappedStatement, Object... params) throws Exception {
        //获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //构建sql
        BoundSql boundSql = getBoundSql(mappedStatement);
        //封装参数
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        String paramsType = mappedStatement.getParamsType();
        Class<?> paramsClass = getClassType(paramsType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            String fieldName = parameterMappings.get(i).getContent();
            Field declaredField = paramsClass.getDeclaredField(fieldName);
            declaredField.setAccessible(true);
            Object value = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,value);
        }
        //查询
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        String resultType = mappedStatement.getResultType();
        Class<?> resultClass = getClassType(resultType);
        List<T> list = new ArrayList<>();
        //封装结果集
        while (resultSet.next()){
            T resultObject = (T) resultClass.getConstructor().newInstance();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i + 1);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(resultObject,value);
            }
            list.add(resultObject);
        }
        return list;
    }

    @Override
    public int update(MappedStatement mappedStatement, Object... params) throws Exception {
        //获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //构建sql
        BoundSql boundSql = getBoundSql(mappedStatement);
        //封装参数
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
        String paramsType = mappedStatement.getParamsType();
        Class<?> paramsClass = getClassType(paramsType);
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            String fieldName = parameterMappings.get(i).getContent();
            Field declaredField = paramsClass.getDeclaredField(fieldName);
            declaredField.setAccessible(true);
            Object value = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,value);
        }
        //查询
        return  preparedStatement.executeUpdate();
    }

    private Class<?> getClassType(String paramsType) throws ClassNotFoundException {
        Class<?> aClass = null;
        if (paramsType!=null) {
            aClass = Class.forName(paramsType);
        }
        return aClass;
    }

    private BoundSql getBoundSql(MappedStatement mappedStatement) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String sql = genericTokenParser.parse(mappedStatement.getSql());
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(sql, parameterMappings);
        return boundSql;
    }
}
